package org.jiusan.project.service;

import java.util.Date;
import java.util.List;

import org.jiusan.project.dao.InputArgDao;
import org.jiusan.project.dao.InterfaceInfoDao;
import org.jiusan.project.dao.OutputArgDao;
import org.jiusan.project.entity.InputArg;
import org.jiusan.project.entity.InterfaceInfo;
import org.jiusan.project.entity.OutputArg;

public class InterfaceServiceImpl {
	private InterfaceInfoDao interfaceInfoDao;
	private InputArgDao inputArgDao;
	private OutputArgDao outputArgDao;
	
	public void addInterfaceInfo(InterfaceInfo info){
		//插入数据
		long id = interfaceInfoDao.addInterfaceInfo(info);
		//中间表数据搭建
		disposeInfo(info,id);
		
		//修改关联
		InterfaceInfo params = new InterfaceInfo();
		params.setId(id);
		params.setRelation(id);
		interfaceInfoDao.updateInterfaceInfo(info);
	}
	
	public void editInterfaceInfo(InterfaceInfo info){
		//修改上次数据
		InterfaceInfo fromDB = interfaceInfoDao.getInfoById(info.getId());
		fromDB.setUsed(false);
		interfaceInfoDao.updateInterfaceInfo(fromDB);
		//创建新数据
		info.setId(null);
		long id = interfaceInfoDao.addInterfaceInfo(info);
		//中间表搭建
		disposeInfo(info,id);
	}
	
	public void deleteInterfaceInfo(Long id,Long userId){
		//修改上次数据
		InterfaceInfo fromDB = interfaceInfoDao.getInfoById(id);
		fromDB.setUpdateTime(new Date());
		fromDB.setUpdateId(userId);
		fromDB.setDelete(false);
		interfaceInfoDao.updateInterfaceInfo(fromDB);
	}
	//根据id查找
	public InterfaceInfo getInterfaceInfoById(Long id){
		InterfaceInfo info = interfaceInfoDao.getInterfaceInfoById(id);
		return info;
	}
	//根据relation查找
	public List<InterfaceInfo> getInterfaceInfoRelationList(Long relation){
		List<InterfaceInfo> list = interfaceInfoDao.getInterfaceInfoRelationList(relation);
		return list;
	}
	
	/**
	 * 获取接口列表 只显示启用状态下
	 * @return
	 */
	public List<InterfaceInfo> getList(){
		List<InterfaceInfo> list = interfaceInfoDao.getList();
		return list;
	}
	
	private void disposeInfo(InterfaceInfo info,long id){
		List<InputArg> inputArgs = info.getInputArgs();
		for (InputArg inputArg : inputArgs) {
			inputArgDao.insert(inputArg.getId(),id);
		}
		List<OutputArg> outputArgs = info.getOutputArgs();
		for (OutputArg outputArg : outputArgs) {
			outputArgDao.insert(outputArg.getId(),id);
		}
		
	}
}
